package com.srv.servlet;

import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.srv.ContentType;
import com.srv.TheException;
import com.srv.model.ID;
import com.srv.model.Node;
import com.srv.model.Resource;
import com.srv.model.Travel;
import com.srv.model.User;
import com.srv.persistence.PersistenceFactory;
import com.srv.service.IDService;
import com.srv.service.NodeService;
import com.srv.service.TravelService;

public class ServletNodeUpdate extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 11111111111111L;

	private static Log log = LogFactory.getLog(ServletNodeUpdate.class);
	
	private final static String FIELD_NAME_TEXT="text";
	private final static String FIELD_NAME_IMG="img";
	private final static String FIELD_NAME_RECORD="record";
	private final static String FIELD_NAME_LAT="lat";
	private final static String FIELD_NAME_LONG="long";
	private final static int MAX_TEXT_LONG=140;
	/**
	---- url 参数	<br/> 
	Id,必须，String  <br/>	
	text,可选，String，必须做URLencode，内容不超过140个汉字<br/>
	img, 可选，binary，仅支持JPEG、GIF、PNG格式，大小小于5M<br/>
	record,可选，binary，仅支持JPEG、GIF、PNG格式，大小小于5M<br/>
	lat,可选,float,纬度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0<br/>
	long,可选,float,经度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0。<br/>
    */
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		 
		 try{
				response.setContentType(ConstText.TextHtml);
				ResponseResult result = new ResponseResult();
				User theUser = RequestTool.getAccessUser(request);			
				//未登陆
				if(theUser==null){				
					result.theResult = ResponseResult.RESULT_FAIL;//结果失败
					result.theMessageObj = ConstText.NotLogin;
					ResponseTool.repsone(request,response,result);
					return;
				}									 
				 
				 //----------------------------- file 
				 request.setCharacterEncoding(ConstText.UTF8);
				 DiskFileItemFactory factory = new DiskFileItemFactory();
				 factory.setSizeThreshold(1024*1024*5);//5MB
				 //factory.setRepository(..)
				 ServletFileUpload upload = new ServletFileUpload(factory);
				 //解析POST过来的参数，保存文件
				 List items = upload.parseRequest(request);// 上传文件解析
		         Iterator itr = items.iterator();// 枚举方法	
		         HashMap<String,FileItem> hm_textForm = new HashMap<String,FileItem>();//存放text的Field
		         HashMap<String,FileItem> hm_fileForm = new HashMap<String,FileItem>();//存放file的Field
		         while (itr.hasNext()) {
		        	 FileItem item = (FileItem) itr.next();
		        	 log.debug("field name = "+item.getFieldName()+", name= "+item.getName());		        	 
		        	// 判断是文件还是文本信息
		             if (item.isFormField()) {
		            	 hm_textForm.put(item.getFieldName(), item);		            	
		             }
		             else{
		            	 hm_fileForm.put(item.getFieldName(), item);
		             }
		         }
		       //参数检查，id为node的id
				 String nid = hm_textForm.get(ConstText.Id)==null?null:hm_textForm.get(ConstText.Id).getString(ConstText.UTF8);
				 ID idObj = IDService.getID(nid);
				 if(idObj==null){
					 result.theResult = ResponseResult.RESULT_FAIL;//结果失败
					 result.theMessageObj=ConstText.ID_IS_INVALID;
					 ResponseTool.repsone(request,response,result);
					 return;
				 }				 
				 Node theOldNode = NodeService.getNode(nid);	//有可能为null			 				 
				 Node theNewNode = new Node();
				 theNewNode.pid = theUser.pid;
				 theNewNode.nodeID = nid;
				 theNewNode.travelID = idObj.extend_1;
				 theNewNode.createTime = idObj.createTime;//创建时间为第1次获取的时间
				 itr = hm_textForm.keySet().iterator();
		         while (itr.hasNext()) {
		        	 if(!dealTextField(request,response,(FileItem)hm_textForm.get(itr.next()),theNewNode,result)){
		        		 return;
		        	 }
		         }
		         itr = hm_fileForm.keySet().iterator();
		         while (itr.hasNext()) {		        	 
		        	 FileItem item = (FileItem) hm_fileForm.get(itr.next());	
		        	 log.debug(item.getContentType());
		        	 
		        	//图片文件
                     if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_IMG)){
                    	 log.debug(item.getName()+" img, size is  "+item.getSize());
                    	//item.getContentType();
                    	if(item.getSize()>0){
                    		Resource resource = new Resource();
                    		resource.id = theNewNode.nodeID;
                    		resource.name = item.getName();
                    		resource.content = item.get();
                    		resource.contentType = ContentType.getInt(item.getContentType());
                    		theNewNode.img_Inner_URI=PersistenceFactory.getResourcePersistence().save(resource);
                    		theNewNode.img_public_URI="/s/res?id=".concat(resource.id).concat("&name=").concat(resource.name);
                    	}                    	
                     	continue;
                     } 
                     //声音文件
                     if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_RECORD)){
                    	 log.debug(item.getName()+" record, size is  "+item.getSize());
                    	 if(item.getSize()>0){
                    		 Resource resource = new Resource();
                     		 resource.id = theNewNode.nodeID;
                     		 resource.name = item.getName();
                     		 resource.content = item.get();
                     		 resource.contentType = ContentType.getInt(item.getContentType());
                     		theNewNode.record_Inner_URI=PersistenceFactory.getResourcePersistence().save(resource);
                     		theNewNode.record_public_URI="/s/res?id=".concat(resource.id).concat("&name=").concat(resource.name);
                    	 }                    	 
                    	 continue;
                     } 
		         }
		        //update
		        NodeService.updateNode(theOldNode, theNewNode);
				 //如果是第1次上载
		        Travel theTravel=TravelService.getTravel(theNewNode.pid, theNewNode.travelID);
		        if(theTravel==null){
		        	theTravel = new Travel();
		        	theTravel.pid = theNewNode.pid;
		        	theTravel.travelID = theNewNode.travelID;
		        	theTravel.createTime = IDService.getID(theTravel.travelID).createTime;//创建时间为第1次获取的时间
		        	TravelService.save(theTravel);
		        }
		        result.theResult = ResponseResult.RESULT_OK;//结果正常
		        result.theMessageObj= null;
		        ResponseTool.repsone(request,response,result);
	   						               
			}catch(TheException te){
				log.error("error: "+te.getMessage());
			}catch(Exception e){
				e.printStackTrace();
				log.error("error: "+e.getMessage());				
			}
    
		
	}
	private boolean dealTextField(HttpServletRequest request,HttpServletResponse response,FileItem item,Node theNode,ResponseResult result) throws ServletException, IOException{
		//为空，不做任何事情
		if(item.getString()==null&&item.getString().length()==0){
   		  return true;
   	 	}
		log.debug(item.getFieldName()+" = "+item.getString(ConstText.UTF8));
	   	 //维度
	   	 if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_LAT)){		            		 
	   		//检查是否合法的值
	   			try{
	   				theNode.latitude=Float.parseFloat(item.getString(ConstText.UTF8));
	   			}catch(java.lang.NumberFormatException ne){
	   				result.theResult = ResponseResult.RESULT_FAIL;//结果失败
	   				result.theMessageObj = ConstText.PARAMETER_IS_INVALID;
	   				ResponseTool.repsone(request,response,result);
	   				return false;
	   			}	   			
	   			return true;
	   	 }
	   	//经度
	   	 if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_LONG)){		            		 
	   		//检查是否合法的值
	   			try{
	   				theNode.longitude=Float.parseFloat(item.getString(ConstText.UTF8));
	   			}catch(java.lang.NumberFormatException ne){
	   				result.theResult = ResponseResult.RESULT_FAIL;//结果失败
	   				result.theMessageObj = ConstText.PARAMETER_IS_INVALID;
	   				ResponseTool.repsone(request,response,result);
	   				return false;
	   			}	   			
	   			return true; 
	   	 }
	   	//文本
	   	 if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_TEXT)){		            		 	   			   			
   				theNode.textContext=item.getString(ConstText.UTF8);
   				if(theNode.textContext.length()>MAX_TEXT_LONG){
   					result.theResult = ResponseResult.RESULT_FAIL;//结果失败
	   				result.theMessageObj = ConstText.PARAMETER_TOO_LONG;
	   				ResponseTool.repsone(request,response,result);
	   				return false;
   				}	   				
	   			return true;
	   		 
	   	 }
		return true;
	}
//	/**
//	 * 处理文件上传.
//	 * @param request
//	 * @param response
//	 * @throws ServletException
//	 * @throws IOException
//	 */
//	
//	public void deal(String nodeID,HttpServletRequest request, HttpServletResponse response)
//	throws ServletException, IOException {		 
//		 DiskFileItemFactory factory = new DiskFileItemFactory();
//		 ServletFileUpload upload = new ServletFileUpload(factory);
//		 try {
//	            List items = upload.parseRequest(request);// 上传文件解析
//	            Iterator itr = items.iterator();// 枚举方法
//	            while (itr.hasNext()) {
//	                FileItem item = (FileItem) itr.next();
//	                if (item.isFormField()) {// 判断是文件还是文本信息
//	                    System.out.println("表单参数名:" + item.getFieldName()
//	                            + "，表单参数值:" + item.getString("UTF-8"));
//	                }
//	                //文件.
//	                else {
//	                    if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件	                    	
//	                    	//图片
//	                        if(item.getFieldName().equalsIgnoreCase(FIELD_NAME_IMG)){
//	                        	
//	                        }
//	                    	System.out.println("上传文件的大小:" + item.getSize());
//	                        System.out.println("上传文件的类型:" + item.getContentType());
//	                        // item.getName()返回上传文件在客户端的完整路径名称
//	                        System.out.println("上传文件的名称:" + item.getName());
//	                        // 此时文件暂存在服务器的内存当中
//
//	                        File tempFile = new File(item.getName());// 构造临时对象
//	                        
//	                        File file = new File("d:/tmp/"+item.getName(),
//	                                tempFile.getName());	                        
//	                        // 获取根目录对应的真实物理路径
//	                        item.write(file);// 保存文件在服务器的物理磁盘中
//	                        request.setAttribute("upload.message", "上传文件成功！");// 返回上传结果
//	                    } 
//	                }
//	            }
//	        } catch (Exception e) {
//	            e.printStackTrace();
//	            request.setAttribute("upload.message", "上传文件失败！");
//	        }
//	        request.getRequestDispatcher("/uploadResult.jsp").forward(request,
//	                response);
//	    }
//	/**
//	 * 处理文件上传.
//	 * @param request
//	 * @param response
//	 * @throws ServletException
//	 * @throws IOException
//	 */
//	
//	public void doFileUpload_1(HttpServletRequest request, HttpServletResponse response)
//	throws ServletException, IOException {		 
//		 DiskFileItemFactory factory = new DiskFileItemFactory();
//		 ServletFileUpload upload = new ServletFileUpload(factory);
//		 try {
//	            List items = upload.parseRequest(request);// 上传文件解析
//	            Iterator itr = items.iterator();// 枚举方法
//	            while (itr.hasNext()) {
//	                FileItem item = (FileItem) itr.next();
//	                if (item.isFormField()) {// 判断是文件还是文本信息
//	                    System.out.println("表单参数名:" + item.getFieldName()
//	                            + "，表单参数值:" + item.getString("UTF-8"));
//	                } else {
//	                    if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件
//	                        System.out.println("上传文件的大小:" + item.getSize());
//	                        System.out.println("上传文件的类型:" + item.getContentType());
//	                        // item.getName()返回上传文件在客户端的完整路径名称
//	                        System.out.println("上传文件的名称:" + item.getName());
//	                        // 此时文件暂存在服务器的内存当中
//
//	                        File tempFile = new File(item.getName());// 构造临时对象
//	                        
//	                        File file = new File("d:/tmp/"+item.getName(),
//	                                tempFile.getName());	                        
//	                        // 获取根目录对应的真实物理路径
//	                        item.write(file);// 保存文件在服务器的物理磁盘中
//	                        request.setAttribute("upload.message", "上传文件成功！");// 返回上传结果
//	                    } else {
//	                        request.setAttribute("upload.message", "没有选择上传文件！");
//	                    }
//	                }
//	            }
//	        } catch (Exception e) {
//	            e.printStackTrace();
//	            request.setAttribute("upload.message", "上传文件失败！");
//	        }
//	        request.getRequestDispatcher("/uploadResult.jsp").forward(request,
//	                response);
//	    }

	 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
		 doPost(request, response);
	 }

}
